package com.xiaoma.verbal.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.xiaoma.tpo.domain.User;
import com.xiaoma.tpo.service.UserService;
import com.xiaoma.tpo.utils.Pager;
import com.xiaoma.verbal.component.AsynPushClient;
import com.xiaoma.verbal.dao.FctForecastDao;
import com.xiaoma.verbal.dao.FctQuestionDao;
import com.xiaoma.verbal.dao.PrctPracticeAudioDao;
import com.xiaoma.verbal.dao.QuClassicDao;
import com.xiaoma.verbal.dao.QuQuestionDao;
import com.xiaoma.verbal.dao.QuTagDao;
import com.xiaoma.verbal.dao.QuTpoDao;
import com.xiaoma.verbal.domain.FctForecast;
import com.xiaoma.verbal.domain.FctQuestion;
import com.xiaoma.verbal.domain.PrctPracticeAudio;
import com.xiaoma.verbal.domain.QuClassic;
import com.xiaoma.verbal.domain.QuQuestion;
import com.xiaoma.verbal.domain.QuTpo;
import com.xiaoma.verbal.dto.CorrectedAudioVo;
import com.xiaoma.verbal.dto.QuTagVo;
import com.xiaoma.verbal.utils.Constants;
import com.xiaoma.verbal.utils.DateUtil;
import com.xiaoma.verbal.utils.Pagination;

@Service
public class PrctPracticeAudioService {
	@Autowired
	private PrctPracticeAudioDao prctPracticeAudioDao;
	@Resource
	private PrctPracticeService prctPracticeService;
	@Resource
	private PrctAssistantService prctAssistantService;
	@Resource
	private UserService userService;
	@Resource
	private TaskExecutor taskExecutor;
	@Autowired
	private ServiceApiService serviceApiService;
	@Autowired
	private AsynPushClient asynPushClient;
	@Autowired
	private FctQuestionDao fctQuestionDao;
	@Autowired
	private QuClassicDao quClassicDao;
	@Autowired
	private QuTpoDao quTpoDao;
	@Autowired
	private FctForecastDao fctForecastDao;
	@Autowired
	private QuTagDao quTagDao;
	@Autowired
	private QuQuestionDao quQuestionDao;

	public PrctPracticeAudio save(Integer userId, String url, Integer recordType, String uuid) {
		PrctPracticeAudio audio = new PrctPracticeAudio();
		audio.setUserId(userId);
		audio.setAudioUrl(url);
		audio.setCreateTime(new Date());
		audio.setUpdateTime(audio.getCreateTime());
		audio.setRecordType(recordType);
		audio.setUuid(uuid);
		audio.setId(this.prctPracticeAudioDao.insert(audio));
		this.prctPracticeService.increaseTotal(userId);
		return audio;
	}

	public PrctPracticeAudio save(PrctPracticeAudio audio) {
		audio.setCreateTime(new Date());
		audio.setUpdateTime(audio.getCreateTime());
		audio.setStatus(1);
		audio.setId(this.prctPracticeAudioDao.insert(audio));
		this.prctPracticeService.increaseTotal(audio.getUserId());
		return audio;
	}

	public Pagination list(Integer userId, String questionNum, String uuid, Integer status, Integer pageNo, Integer pageSize) {
		// TODO Auto-generated method stub
		if (pageNo == null || pageSize == null) {
			pageNo = 1;
			pageSize = 10;
		}
		Pagination pager =  prctPracticeAudioDao.queryPageList(userId, questionNum, status, pageNo, pageSize);
		judgeClass(pager);
		return pager;

	}
	//判断录音是属于 黄金口语、tpo 或者 机经中的一个
	public void judgeClass(Pagination pager){
		List<CorrectedAudioVo> list = (List<CorrectedAudioVo>)pager.getList();
		for(CorrectedAudioVo correctedAudioVo : list){
			String uuid = correctedAudioVo.getUuid();
			//判断是否是机经，是就结束
			FctQuestion fctQuestion = new FctQuestion();
			fctQuestion.setUuid(uuid);
			List<FctQuestion> lFctQuestions = fctQuestionDao.findByColumns(fctQuestion);		
			if(lFctQuestions != null && lFctQuestions.size()>0){
				FctForecast fctForecast = new FctForecast();
				fctForecast.setId(lFctQuestions.get(0).getForecastId());
				List<FctForecast> lfctForecasts = fctForecastDao.findByColumns(fctForecast);
				String date= "";
				if(lfctForecasts != null && lfctForecasts.size()>0){
					 date =  DateUtil.dateToStr(lfctForecasts.get(0).getTimeRange1(), "MM月dd日");
				}
				String num = correctedAudioVo.getQuestionNum();
				String[] str = num.split("_");
				String index = str[1];
				correctedAudioVo.setClassName("机经 "+date+" "+index);
				continue;
			}
			//判断是否是黄金口语 是就结束
			QuClassic quClassic = new QuClassic();
			quClassic.setUuid(uuid);
			List<QuClassic> lQuClassics = quClassicDao.findByColumns(quClassic);
			if(lQuClassics != null && lQuClassics.size()>0){
				//判断黄金口语属于哪个类别 例如 ：活动类，任务类
				List<QuTagVo> lQuTagVos= quTagDao.findTagByQuestionId(correctedAudioVo.getQuestionId());
				QuTagVo qutagVo = lQuTagVos.get(0);
				String num = correctedAudioVo.getQuestionNum();
				String[] str = num.split("_");
				String index = str[1];
				correctedAudioVo.setClassName("黄金口语 "+qutagVo.getTagText()+" "+index);
				continue;
				
			}
			//判断是不是TPO 是就结束
			
			QuTpo quTpo = new QuTpo();
			quTpo.setUuid(uuid);
			List<QuTpo> lQuTpos = quTpoDao.findByColumns(quTpo);
			if(lQuTpos != null && lQuTpos.size()>0){
				correctedAudioVo.setClassName("TPO "+lQuTpos.get(0).getTpoNum()+" "+lQuTpos.get(0).getTaskNum());
			}
		}
		
	}


		

	public CorrectedAudioVo getByUuid(Integer userId, String uuid) {
		CorrectedAudioVo correctedAudioVo = this.prctPracticeAudioDao.getByUuid(userId, uuid);
		CorrectedAudioVo correctedAudioVo2 = null;
		QuQuestion quQuestion = new QuQuestion();
		if(correctedAudioVo == null){
			return null;
		}
		quQuestion.setQuestionNum(correctedAudioVo.getQuestionNum());
		List<QuQuestion> questions = quQuestionDao.findByColumns(quQuestion);
		if(questions != null && questions.size() > 0){
			correctedAudioVo.setQuestionId(questions.get(0).getId());
			if(correctedAudioVo != null ){
				Pagination pager = new Pagination();
				List<CorrectedAudioVo> list = new ArrayList<CorrectedAudioVo>();
				list.add(correctedAudioVo);
				pager.setList(list);
				judgeClass(pager);
				List<CorrectedAudioVo> lCorrectedAudioVos = (List<CorrectedAudioVo>)pager.getList();
				correctedAudioVo2 = lCorrectedAudioVos.get(0);
			}
		}
		return correctedAudioVo2;
	}
	//新的
	public CorrectedAudioVo getByUuidNew(Integer userId, String uuid) {
		return this.prctPracticeAudioDao.getByUuidNew(userId, uuid);
	}

	public CorrectedAudioVo getVoById(Integer id) {
		return this.prctPracticeAudioDao.getVoById(id);
	}

	public void sendToAssistantPerformance(final PrctPracticeAudio audio) {
		taskExecutor.execute(new Runnable() {

			@Override
			public void run() {
				List<Object[]> messages = new ArrayList<Object[]>();
				// TODO Auto-generated method stub
				String postUrl = serviceApiService.findByUniqueCode(Constants.API_XBPG).getApi();

				Object[] parms = new Object[3];
				parms[0] = postUrl;
				parms[1] = toJsonString(getVoById(audio.getId()));
				parms[2] = audio.getId();
				messages.add(parms);
				if (messages.size() > 0) {
					asynPushClient.init(messages);
					try {
						asynPushClient.asynPost();
					} catch (Exception e) {
						e.printStackTrace();
						// TODO: handle exception
					}

				}
			}
		});
	}

	public String toJsonString(CorrectedAudioVo audio) {

		JSONObject jbean = new JSONObject();
		jbean.put("productionName", "XMTOEFL_XB_21");
		jbean.put("moduleName", "XMTOEFL_XB_21_ORAL");
		jbean.put("navigation", getNavigation(audio.getRecordType(), audio.getUuid()));
		jbean.put("questionId", audio.getQuestionId());
		jbean.put("question", audio.getContent());
		jbean.put("questionSeqNum", audio.getQuestionNum());
		jbean.put("answerId", audio.getId());
		jbean.put("type", 1);
		jbean.put("answer", audio.getAudioUrl());
		User user = userService.findById(audio.getUserId());
		jbean.put("studentId", user.getId());
		jbean.put("studentNickName", user.getName());
		jbean.put("studentAvatar", user.getAvatar());
		jbean.put("submitTime", audio.getCreateTime());
		return jbean.toString();

	}

	public String getNavigation(Integer recordType, String uuid) {
		String navi = "机经";
		if (recordType != null) {
			if (recordType == 1) {
				FctQuestion fq = new FctQuestion();
				fq.setUuid(uuid);
				List<FctQuestion> list = fctQuestionDao.findByColumns(fq);
				if (!CollectionUtils.isEmpty(list)) {
					fq = list.get(0);
					Integer fcid = fq.getForecastId();
					FctForecast fctf = fctForecastDao.getById(fcid);
					if (fctf != null && fctf.getTimeRange1() != null) {
						SimpleDateFormat formate = new SimpleDateFormat("yyyy年MM月dd日");
						navi = "机经" + formate.format(fctf.getTimeRange1());
					}

				}
			} else if (recordType == 2) {
				navi = "黄金口语";
			} else if (recordType == 3) {
				navi = "TPO口语";
			}
		}
		return navi;
	}

	public Pager list(Integer page, Integer pageSize) {
		// TODO Auto-generated method stub
		if (page == null || page == 0) {
			page = 1;
			pageSize = 50;
		}
		Pager pager = prctPracticeAudioDao.queryPageList((page - 1) * pageSize, pageSize);

		return pager;
	}
	//新的 根据userID questionNum classId  判断是否存在这条录音
	public boolean findByUserIdAndQuestionNumAndClassId(Integer userId,
			String questionNum, Integer clsClassId) {
		boolean b = prctPracticeAudioDao.findbyClsIdAndQuestionNumAndUserId(clsClassId, questionNum, userId);
		return b;
	}

}
